import React, { Component } from 'react';
import ReactDom from 'react-dom';
import util from "@/common/util";
import layer from "@/common/layer";
import cakeflakes from "@/common/cakeflakes";
import axios from 'axios';
import ReactSwiper from 'reactjs-swiper';
import jquery from 'jquery';


class Crabshare extends Component {
    constructor(props) {
        super(props);
        this.state = {
            prodetail: {},
            iscollect: false
        }
    }

    async sendcode() {
        var wechatcode = util.getQuery().code;
        let res = await util.rjax({
            url: '/wxAuthenticate/getOpenId?code=' + wechatcode,
            type: 'post',
        }).catch((res) => {
            console.log("catch:" + res)
        })

        if (res) {
            console.log("if(res):" + res)
            sessionStorage.setItem("otheropenid", res.data.openId)
            // alert("sessionStorage.getItem('otheropenid'):  " + sessionStorage.getItem('otheropenid'))

        }
    }

    componentDidMount() {
        if (util.getQuery().code) {
            // alert("sessionStorage.getItem('otheropenid'):  " + sessionStorage.getItem('otheropenid'))
            // alert("sessionStorage.getItem('openid'):  " + sessionStorage.getItem('openid'))
            // alert("sessionStorage.getItem('id'):  " + sessionStorage.getItem('id'))
            var otheropenid = sessionStorage.getItem("otheropenid")
            if (!otheropenid || otheropenid === 'null') {
                this.sendcode()
            }
        }
        else {
            sessionStorage.setItem('id', util.getQuery().id)
            sessionStorage.setItem('openid', util.getQuery().uid)
            window.location.href = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxeaccffdd3826280c&redirect_uri=http%3a%2f%2fwww.rongsue.com%2fwechat%2fcrabshare.html&response_type=code&scope=snsapi_userinfo&state=#wechat_redirect"
        }

        let getconfig = async function () {
            let res = await util.rjax({
                url: "/wx/getwx?url=" + encodeURIComponent(window.location.href.split('#')[0]),
                type: "POST"
            })

            if (res) {
                wx.config({
                    debug: false,
                    appId: 'wxeaccffdd3826280c', // 必填，公众号的唯一标识
                    timestamp: parseInt(res.data.timestamp),// 必填，生成签名的时间戳
                    nonceStr: res.data.nonceStr,// 必填，生成签名的随机串
                    signature: res.data.signature,// 必填，签名
                    jsApiList: ['onMenuShareTimeline', 'onMenuShareAppMessage', 'onMenuShareQQ', 'onMenuShareWeibo', 'onMenuShareQZone']// 必填，需要使用的JS接口列表
                })
            }
        }
        getconfig()

        var proid = sessionStorage.getItem("id");
        var openid = sessionStorage.getItem("openid");
        wx.ready(function () {
            //朋友圈
            wx.onMenuShareTimeline({// 获取“分享到朋友圈”按钮点击状态及自定义分享内容接口（即将废弃）
                title: '苏e融喜迎国庆！助力夺大奖！', // 分享标题
                link: 'http://www.rongsue.com/wechat/crabshare.html?id=' + proid + "&uid=" + openid, // 分享链接
                imgUrl: 'http://img0.rongsue.com/FoCM38f9Tm0cNkvg8NasnlmGqEsh',
                success: function (res) {
                    // that.setState({ share: true })
                    // alert("已分享")
                },
                cancel: function (res) {
                    // alert('取消了分享')
                },
                fail: function (res) {
                    alert(JSON.stringify(res));
                }
            });

            //朋友
            wx.onMenuShareAppMessage({//获取“分享给朋友”按钮点击状态及自定义分享内容接口（即将废弃）
                title: '苏e融喜迎国庆！助力夺大奖！', // 分享标题
                desc: '“Disney黄金双挂坠项链、阳澄湖大闸蟹、九阳多功能家电烤箱、车载净化器....”', // 分享描述
                link: 'http://www.rongsue.com/wechat/crabshare.html?id=' + proid + "&uid=" + openid, // 分享链接
                imgUrl: 'http://img0.rongsue.com/FoCM38f9Tm0cNkvg8NasnlmGqEsh', // 分享图标
                type: '', // 分享类型,music、video或link，不填默认为link
                dataUrl: '', // 如果type是music或video，则要提供数据链接，默认为空
                success: function () {
                    // 用户确认分享后执行的回调函数
                    // that.setState({ share: true })
                    // alert("已分享")
                },
                cancel: function () {
                    // 用户取消分享后执行的回调函数
                    // alert('取消了分享')
                },
                fail: function (res) {
                    alert(JSON.stringify(res));
                }
            });
        });

        var that = this
        jquery(".btnwrite").click(function () {
            if (jquery('.btnwrite').html() === '帮好友助力') {
                that.assist()
            } else if (jquery('.btnwrite').html() === '我也想夺免费大奖') {
                sessionStorage.clear();
                window.location.href = './crabactivity.html'
            }
        })

        var timebool = this.checkTime('2018-09-26', '2018-09-30');//注意：日期用“-”分隔
        if (timebool == 1) {
            jquery('.btncall').attr("src", '/assets/wechat/btn_disabled.png')
            jquery('.btnwrite').html('活动还未开始')
            jquery('.collectimg').css('display', 'none')
        } else if (timebool == 2) {
            jquery('.btncall').attr("src", '/assets/wechat/btn_disabled.png')
            jquery('.btnwrite').html('活动已结束')
            jquery('.collectimg').css('display', 'none')
        }
        else if (timebool == 3) {
            jquery('.collectimg').css('display', 'none')
        }

        this.prodetail()
        this.iscollect()
    }


    async assist() {
        let sendobj = {
            openId: sessionStorage.getItem('openid'),
            otherOpenId: sessionStorage.getItem('otheropenid'),
            prizeId: sessionStorage.getItem('id')
        }
        let res = await util.rjax({
            url: '/assistFriend/assist',
            type: 'post',
            data: sendobj
        }).catch((e) => {
            if (e.data.code === 10011050) {//已经助力过一次,不能继续助力
                layer.open({
                    content: e.data.msg,
                    btn: "好的"
                })
                jquery('.btnwrite').html("我也想夺免费大奖")
            }
        })
        if (res) {
            layer.open({
                content: "帮好友助力成功啦！",
                btn: "好的"
            })
            jquery('.btnwrite').html("我也想夺免费大奖")
        }
    }

    async prodetail() {
        var proid = sessionStorage.getItem("id");
        let res = await util.rjax({
            url: '/prize/getPrize/?prizeId=' + proid + '&type=1',
            type: 'get',
        })
        this.setState({ prodetail: res.data });
    }

    async iscollect() {
        var openid = sessionStorage.getItem("openid");
        var proid = sessionStorage.getItem("id");
        let res = await util.rjax({
            url: '/assist/assistCount?prizeId=' + proid + '&openId=' + openid,
            type: 'get',
        })
        if (!res.data - this.state.prodetail.total >= 0) {
            this.setState({ iscollect: true });
        } else {
            this.setState({ iscollect: false });
        }
    }

    checkTime(stime, etime) {
        //开始时间
        var arrs = stime.split("-");
        var startTime = new Date(arrs[0], arrs[1], arrs[2]);
        var startTimes = startTime.getTime();
        //结束时间
        var arre = etime.split("-");
        var endTime = new Date(arre[0], arre[1], arre[2]);
        var endTimes = endTime.getTime();
        //当前时间
        var thisDate = new Date();
        var thisDates = thisDate.getFullYear() + "-0" + (thisDate.getMonth() + 1) + "-" + thisDate.getDate();
        var arrn = thisDates.split("-");
        var nowTime = new Date(arrn[0], arrn[1], arrn[2]);
        var nowTimes = nowTime.getTime();

        if (nowTimes < startTimes) {
            return 1;
        } else if (nowTimes > endTimes) {
            return 2;
        } else {
            return 3;
        }
    }


    render() {

        return (
            <div>
                <div id="crab">
                    <div className='crabtop'>
                        <img className="toppic" src="/assets/wechat/crabtop_pic.png" alt="" />
                    </div>
                    <div className="crabcard">
                        <p className="wantto">我很想要这个,请帮我助力吧！</p>
                        <div style={{ position: 'relative' }}>
                            <img className="crabpic" src={this.state.prodetail.image} alt="" />
                        </div>
                        <p className="crabintr">{this.state.prodetail.introduction}</p>
                        <p className="comeon">快来帮好友助力夺免费大奖！</p>
                        <p className="comeon">先到先得</p>
                        <div style={{ position: 'relative' }}>
                            <img className="btncall" src="/assets/wechat/btn_helpfrd.png" alt="" />
                            <p className="btnwrite">{this.state.iscollect ? ' 我也想夺免费大奖' : '帮好友助力'}</p>
                        </div>
                        <img className="collectimg" style={{ 'display': this.state.iscollect ? 'block' : 'none' }} src="/assets/wechat/allcollect.png" alt="" />
                    </div>
                    {/* <img className="bottompic" src="/assets/wechat/bottom_pic.png" alt="" /> */}
                </div>
            </div>
        )
    }
}
ReactDom.render(<Crabshare />, document.getElementById("app"));